import React, { useState, useRef } from 'react';
import { Image, Alert, Button, Tooltip, Modal, message, Popconfirm } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { deleteother_business, transfer_account } from '@/services/business';
import { area, user } from '@/services/basic';
import { connect, history } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import ProDescriptions from '@ant-design/pro-descriptions';
import CompanyName from '@/components/CompanyName';

// type 类型有 table treeselect upload inputnumber datepicker daterange radio select textarea autoinput editor password input

let defaultFields = {
  // "snapshot": {
  //     "value": null,
  //     "type": "recognition",
  //     "title": "营业执照",
  //     "name": [
  //         "snapshot"
  //     ],
  //     "required": true,
  //     "col": { span: 24 }
  // },
  company_name: {
    value: null,
    type: 'input',
    title: '公司全称',
    name: ['company_name'],
    required: true,
  },
  // "legal_person": {
  //     "value": null,
  //     "type": "input",
  //     "title": "公司法人",
  //     "name": [
  //         "legal_person"
  //     ],
  //     "required": false
  // },
  // "address": {
  //     "value": null,
  //     "type": "input",
  //     "title": "公司地址",
  //     "name": [
  //         "address"
  //     ],
  //     "required": false
  // },
  // "enterprise_credit_code": {
  //     "value": null,
  //     "type": "input",
  //     "title": "统一社会信用代码",
  //     "name": [
  //         "enterprise_credit_code"
  //     ],
  //     "required": false
  // },
  customer_name: {
    value: null,
    type: 'input',
    title: '联系人',
    name: ['customer_name'],
    required: true,
  },
  customer_phone: {
    value: null,
    type: 'input',
    title: '联系人手机号',
    width: 120,
    name: ['customer_phone'],
    required: true,
  },
  area_id: {
    value: null,
    type: 'select',
    title: '区域',
    name: ['area_id'],
    required: true,
    linked: true,
    options: {
      database: area,
      params: { is_all: 1 },
    },
  },
  is_coordination: {
    value: null,
    type: 'select',
    title: '是否有经办人',
    name: ['is_coordination'],
    required: true,
    linked: true,
    options: [
      {
        label: '有',
        value: true,
      },
      {
        label: '没有',
        value: false,
      },
    ],
  },
  coordination_id: {
    value: null,
    type: 'select',
    title: '经办人',
    name: ['coordination_id'],
    required: false,
    options: {
      database: user,
      params: { is_all: 1 },
    },
    belinked: {
      hides: [
        //可以多个条件并存 数组内添加即可
        {
          name: 'is_coordination', //联动的是哪个formitem
          equalvalue: [false], //这个formitem值为多少 hide
          required: true,
        },
      ],
    },
  },
  auxiliary_coordination_id: {
    value: null,
    type: 'select',
    title: '辅助经办人',
    name: ['auxiliary_coordination_id'],
    required: false,
    options: {
      database: user,
      params: { is_all: 1 },
    },
    belinked: {
      hides: [
        //可以多个条件并存 数组内添加即可
        {
          name: 'is_coordination', //联动的是哪个formitem
          equalvalue: [false], //这个formitem值为多少 hide
          required: true,
        },
      ],
    },
  },
};

let options = [
    {
      id: 'pending',
      name: '进行中',
    },
  ],
  valueEnum = {
    pending: {
      text: '接单人进行中',
    },
    coordination_pending: {
      text: '经办人进行中',
    },
    auxiliary_coordination_pending: {
      text: '辅助经办人进行中',
    },
    cancel: {
      text: '已取消',
    },
    completed: {
      text: '已完成',
    },
  };

function Second(props) {
  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState(defaultFields),
    [iftype, ciftype] = useState({}),
    { row = {} } = props,
    [sd, csd] = useState(false);

  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }

  const columns = [
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'company_name',
      key: 'company_name',
      render: (_, row) => (
        <CompanyName
          row={{ ...row, name: row?.company_name ?? row.name, id: row?.company_id ?? row.id }}
          reload={reload}
        />
      ),
    },
    // {
    //     title: '公司法人',
    //     dataIndex: 'legal_person',
    //     key: 'legal_person',
    //     search: false,
    //     hideInTable: true
    // },
    // {
    //     title: '公司地址',
    //     dataIndex: 'address',
    //     key: 'address',
    //     search: false,
    //     hideInTable: true
    // },
    // {
    //     title: '统一社会信用代码',
    //     dataIndex: 'enterprise_credit_code',
    //     key: 'enterprise_credit_code',
    //     search: false,
    //     hideInTable: true
    // },
    // {
    //     title: '公司营业执照',
    //     dataIndex: 'origin_url',
    //     key: 'origin_url',
    //     render: (_, row) => {
    //         return <Image width={32} height={32} style={{ padding: 2 }} src={row.origin_url}></Image>
    //     },
    //     hideInTable: true
    // },
    {
      title: '联系人',
      dataIndex: 'customer_name',
      key: 'customer_name',
      ellipsis: true,
    },
    {
      title: '联系人手机号',
      width: 120,
      dataIndex: 'customer_phone',
      key: 'customer_phone',
      render: (_, row) => (
        <Tooltip title={row.customer_phone}>
          <a href={`tel:${row.customer_phone}`} className="oneline">
            {row.customer_phone}
          </a>
        </Tooltip>
      ),
    },
    {
      title: '区域名称',
      dataIndex: 'area_name',
      key: 'area_name',
      search: false,
    },
    {
      title: '区域编码',
      dataIndex: 'area_code',
      key: 'area_code',
      search: false,
      hideInTable: true,
    },
    {
      title: '接单人',
      dataIndex: 'user_name',
      key: 'user_name',
      search: false,
    },
    {
      title: '经办人',
      dataIndex: 'coordination_name',
      key: 'coordination_name',
      search: false,
    },
    {
      title: '辅助经办人',
      dataIndex: 'auxiliary_coordination_name',
      key: 'auxiliary_coordination_name',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueType: 'select',
      options: options,
      valueEnum: valueEnum,
      width: 88,
      render: (_, row) => (
        <Tooltip title={valueEnum[row.status]?.text}>
          <div className="oneline">{valueEnum[row.status]?.text}</div>
        </Tooltip>
      ),
    },
    {
      title: '合同协议',
      dataIndex: 'contracts',
      key: 'contracts',
      search: false,
      render: (_, row) => {
        if (!row.contracts) {
          return (
            <Image
              width={32}
              height={32}
              style={{ padding: 2 }}
              src={require('@/assets/default.png')}
            />
          );
        } else {
          return row.contracts.map((it) => {
            return <Image width={32} height={32} src={it.origin_url} style={{ padding: 2 }} />;
          });
        }
      },
      hideInTable: true,
    },
    {
      title: '收款单',
      dataIndex: 'id',
      key: 'id',
      search: false,
      width: 160,
      render: (_, row) => (
        <div>
          <a
            style={{ color: '#f50', marginRight: 12 }}
            onClick={() => {
              ciftype({
                ...iftype,
                val: 'skd',
                title: '收款单',
                curitem: row,
              });
              cvs(true);
            }}
          >
            查看
          </a>
          <a
            onClick={() => {
              history.push({
                pathname: `/finance/receipt`,
                query: {
                  id: row.company_id,
                  service_id: row.service_id,
                  other_business_id: row.id,
                },
              });
            }}
          >
            新增收款单
          </a>
        </div>
      ),
    },
    {
      title: '转代账业务',
      dataIndex: 'ol',
      key: 'ol',
      search: false,
      render: (_, record) => (
        <Popconfirm
          placement="bottom"
          title={'确认转代账业务？'}
          onConfirm={() => {
            transfer_account({ id: record.id }).then((res) => {
              if (res.code == 0) {
                message.success('操作成功');
              }
            });
          }}
          onCancel={() => {
          }}
          okText="确认"
          cancelText="取消"
        >
          <a>确认</a>
        </Popconfirm>
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      width: 340,
      render: (text, record, _, action) => [
        <a
          disabled={record.status != 'pending' || record.user_id != props.user.currentUser.id}
          onClick={() => {
            if (record.status != 'pending' || record.user_id != props.user.currentUser.id) {
              return;
            }
            cvs(true);
            cf((fields) => {
              return {
                annex: {
                  value: null,
                  type: 'upload',
                  title: '业务完成附件',
                  name: ['annex'],
                  required: false,
                  listType: 'img',
                  multiple: true,
                  limit: 20,
                },
              };
            });
            ciftype({
              val: 'afinish',
              id: record.id,
              title: '接单人完成',
            });
          }}
        >
          接单人操作
        </a>,
        <a
          disabled={
            record.status != 'coordination_pending' ||
            record.coordination_id != props.user.currentUser.id
          }
          onClick={() => {
            if (
              record.status != 'coordination_pending' ||
              record.coordination_id != props.user.currentUser.id
            ) {
              return;
            }
            cvs(true);
            cf((fields) => {
              return {
                annex: {
                  value: null,
                  type: 'upload',
                  title: '经办人完成附件',
                  name: ['annex'],
                  required: false,
                  listType: 'img',
                  multiple: true,
                  limit: 20,
                },
              };
            });
            ciftype({
              val: 'bfinish',
              id: record.id,
              title: '经办人完成',
            });
          }}
        >
          经办人操作
        </a>,
        <a
          disabled={
            record.status != 'auxiliary_coordination_pending' ||
            record.auxiliary_coordination_id != props.user.currentUser.id
          }
          onClick={() => {
            if (
              record.status != 'auxiliary_coordination_pending' ||
              record.auxiliary_coordination_id != props.user.currentUser.id
            ) {
              return;
            }
            cvs(true);
            cf((fields) => {
              return {
                annex: {
                  value: null,
                  type: 'upload',
                  title: '辅助经办人完成附件',
                  name: ['annex'],
                  required: false,
                  listType: 'img',
                  multiple: true,
                  limit: 20,
                },
              };
            });
            ciftype({
              val: 'cfinish',
              id: record.id,
              title: '辅助经办人完成',
            });
          }}
        >
          辅助经办人操作
        </a>,
        <Popconfirm
          placement="bottom"
          title={'确认删除该业务？'}
          onConfirm={() => {
            deleteother_business(record.id).then((res) => {
              if (res.code == 0) {
                message.success('操作成功');
                reload();
              }
            });
          }}
          disabled={!options.some((it) => it.id == record.status)}
          okText="删除"
          cancelText="取消"
        >
          <a
            disabled={!options.some((it) => it.id == record.status)}
            style={{ color: !options.some((it) => it.id == record.status) ? '#999' : '#f50' }}
          >
            删除
          </a>
        </Popconfirm>,
      ],
    },
  ];

  let extrarender = [
    <div
      className="action"
      title="新增"
      onClick={() => {
        cvs(true);
        cf(() => {
          for (let i in defaultFields) {
            defaultFields[i].value = null;
            if (i == 'is_accountant') {
              defaultFields[i].value = true;
            }
            if (i == 'is_create_order') {
              defaultFields[i].value = false;
            }
          }
          return { ...defaultFields };
        });
        ciftype({
          val: 'add',
          title: '新增业务',
        });
      }}
    >
      <PlusOutlined />
    </div>,
  ];

  let saveData = (values) => {
    let { dispatch } = props;
    if (iftype.val == 'add') {
      values = {
        ...values,
        service_id: row.id,
      };
      dispatch({
        type: 'business/addother_business',
        payload: values,
      }).then((res) => {
        if (res.code == 0) {
          Modal.confirm({
            title: '操作成功',
            content: '是否立刻新增收款单？',
            okText: '是',
            cancelText: '否',
            onOk: () => {
              history.push({
                pathname: `/finance/receipt`,
                query: {
                  id: res?.data?.company_id,
                  service_id: res?.data?.service_id,
                  other_business_id: res?.data?.id,
                },
              });
            },
            onCancel: () => {
              reload();
              cvs(false);
            },
          });
        }
      });
    } else if (iftype.val == 'afinish') {
      dispatch({
        type: 'business/receiver_submit',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val == 'bfinish') {
      dispatch({
        type: 'business/coordination_submit',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val == 'cfinish') {
      dispatch({
        type: 'business/auxiliary_coordination_submit',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          reload();
          cvs(false);
        }
      });
    }
  };

  return (
    <div>
      <AutoTable
        bordered={false}
        pagetitle={
          <span>
            {row.name}{' '}
            <a
              style={{ fontSize: 14, paddingLeft: 12 }}
              onClick={() => {
                props.close();
              }}
            >
              {' '}
              返回
            </a>
          </span>
        } //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/wbn-api/other_business"
        extraparams={{ service_id: row.id }}
        //withCard={false}
        //cardtitle = "name" //卡片标题
        //cardavatar = "img_url" //卡片头像
      />
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        width={1400}
        destroyOnClose={true}
      >
        {iftype.val == 'skd' ? (
          <div>
            <Alert
              message="显示/隐藏代账公司详情"
              style={{ marginBottom: 20 }}
              showIcon
              type="info"
              action={
                <Button
                  size="small"
                  type="primary"
                  onClick={() => {
                    csd(!sd);
                  }}
                >
                  {!sd ? '显示' : '隐藏'}
                </Button>
              }
            />
            <div
              style={{
                backgroundColor: '#f9f9f9',
                padding: sd ? 12 : 0,
                paddingBottom: 0,
                borderRadius: 8,
                height: sd ? 'auto' : 0,
                transition: 'all 0.4s',
                overflow: 'hidden',
              }}
            >
              <ProDescriptions
                title={`${iftype.curitem.company_name}的详细信息`}
                columns={[...columns.filter((it) => it.key != 'user_name')]}
                column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
                dataSource={iftype.curitem}
              />
            </div>
            <AutoTable
              columns={[
                {
                  title: '本期收费单号',
                  dataIndex: 'settle_id',
                  key: 'settle_id',
                  width: 100,
                  copyable: true,
                  search: false,
                  render: (_, row) => (
                    <span>
                      {row.settle_id ? (Array(5).join(0) + row.settle_id).slice(-5) : '-'}
                    </span>
                  ),
                },
                {
                  title: '公司名称',
                  width: 260,
                  dataIndex: 'company_name',
                  key: 'company_name',
                  render: (_, row) => (
                    <CompanyName
                      row={{
                        ...row,
                        name: row?.company_name ?? row.name,
                        id: row?.company_id ?? row.id,
                      }}
                      reload={reload}
                    />
                  ),
                },
                {
                  title: '应收款',
                  dataIndex: 'receivable',
                  key: 'receivable',
                  search: false,
                },
                {
                  title: '月收费',
                  dataIndex: 'unit_price',
                  key: 'unit_price',
                  search: false,
                },
                {
                  title: '服务开始时间',
                  dataIndex: 'service_start_time',
                  key: 'service_start_time',
                  width: 100,
                  search: false,
                },
                {
                  title: '服务结束时间',
                  dataIndex: 'service_end_time',
                  key: 'service_end_time',
                  width: 100,
                  search: false,
                },
                {
                  title: '接单人',
                  dataIndex: 'user_name',
                  key: 'user_name',
                  search: false,
                },
                {
                  title: '支付周期',
                  dataIndex: 'payment_cycle_name',
                  key: 'payment_cycle_name',
                  search: false,
                },
                {
                  title: '周期月数',
                  dataIndex: 'cycle_num',
                  key: 'cycle_num',
                  search: false,
                },
                {
                  title: '支付类型',
                  dataIndex: 'payment_type',
                  key: 'payment_type',
                  valueType: 'select',
                  options: [
                    {
                      id: 'full',
                      name: '全款',
                    },
                    {
                      id: 'deposit',
                      name: '定金',
                    },
                    {
                      id: 'balance',
                      name: '尾款',
                    },
                  ],
                  valueEnum: {
                    full: {
                      text: '全款',
                    },
                    deposit: {
                      text: '定金',
                    },
                    balance: {
                      text: '尾款',
                    },
                  },
                },
                {
                  title: '收款日期',
                  dataIndex: 'payment_time',
                  key: 'payment_time',
                  width: 100,
                },
                {
                  title: '实际收款',
                  dataIndex: 'actual_receive',
                  key: 'actual_receive',
                },
                {
                  title: '收款方式',
                  dataIndex: 'payment_name',
                  key: 'payment_name',
                },
                {
                  title: '备注',
                  dataIndex: 'remark',
                  key: 'remark',
                  search: false,
                },
                {
                  title: '状态',
                  dataIndex: 'status',
                  key: 'status',
                  valueType: 'select',
                  options: [
                    {
                      id: 'cashiering',
                      name: '出纳审核中',
                    },
                    {
                      id: 'cashier_refuse',
                      name: '出纳拒绝',
                    },
                    {
                      id: 'cache',
                      name: '待激活',
                    },
                  ],
                  valueEnum: {
                    cache: {
                      text: '待激活',
                      status: 'error',
                    },
                    cashiering: {
                      text: '出纳审核中',
                    },
                    cashier_refuse: {
                      text: '出纳拒绝',
                    },
                    accounting: {
                      text: '会计审核中',
                    },
                    account_refuse: {
                      text: '会计拒绝',
                    },
                    completed: {
                      text: '已完成',
                    },
                  },
                  render: (dom, row) => (
                    <div
                      style={{
                        color: row?.status?.indexOf('refuse') != -1 ? 'red' : 'auto',
                        cursor: 'pointer',
                      }}
                      onClick={() => {
                        if (row.status == 'cashier_refuse') {
                          Modal.info({
                            title: '拒绝原因',
                            content: row.cashier_refuse_message,
                            maskClosable: true,
                          });
                        }
                      }}
                    >
                      {dom}
                    </div>
                  ),
                },
              ]}
              path="/wbn-api/payment_order"
              extraparams={{ company_id: iftype.curitem.company_id }}
              withCard={false}
              //cardtitle = "name" //卡片标题
              //cardavatar = "img_url" //卡片头像
            />
          </div>
        ) : iftype.val == 'see' && iftype.curitem ? (
          <ProDescriptions
            title={`${iftype.curitem.company_name}的详细信息`}
            columns={[...columns]}
            column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
            dataSource={iftype.curitem}
          />
        ) : (
          <InitForm
            fields={fields}
            submitData={(values) => {
              saveData(values);
            }}
            onChange={(changedValues, allValues) => {
              //联动操作
            }}
            submitting={
              props.loading.effects['business/dispatchretry'] ||
              props.loading.effects['business/addother_business'] ||
              !vs
            }
            halfsave={false}
          />
        )}
      </Modal>
    </div>
  );
}

export default connect(({ user, business, loading }) => ({
  user,
  business,
  loading,
}))(Second);
